from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer, BadData
from django.conf import settings


def generate_save_user_token(openid):
    '''对用户的open_id进行加密'''
    #1.0创建加密的序列化对象seCrete_key,
    serializers = TJWSSerializer(settings.SECRET_KEY,600)
    #2.0 调用dumps进行加密,加密后的数据时byte类型,所以需要解码
    data = {'openid':openid}
    data=serializers.dumps(data)
    #3.0把加载后的openid返回
    #返回的数据要进行解密
    return data.decode()

def check_save_user_token(access_token):
    '''传入加密的access_token,进行解密'''
    #1.0创建解密的序列化器对象.
    serializers = TJWSSerializer(settings.SECRET_KEY, 600)
    #2.0调用里面的loads方法进行解密
    '''因为设置有过期时间,所以有可能会取不到,就会报错'''
    try:
        data = serializers.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')